/**
 * @program: LeetCode
 * @description: LeetCode : 剑指 Offer 55 - II. 平衡二叉树
 * @author: WXY
 * @create: 2022-12-10 20:31
 * @Version 1.0
 **/


public class Num055_2_isBalanced {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    public boolean isBalanced(TreeNode root) {
        if (root == null)return true;
        Info ans = process(root);
        return ans.isBalance;
    }

    private Info process(TreeNode root) {
        if (root == null) return new Info(true, 0);
        Info leftInfo = process(root.left);
        Info rightInfo = process(root.right);
        int height = Math.max(leftInfo.height, rightInfo.height) + 1;
        if (!leftInfo.isBalance || !rightInfo.isBalance) {
            return new Info(false, height);
        }
        int leftHeight = leftInfo.height;
        int rightHeight = rightInfo.height;
        if (Math.abs(leftHeight - rightHeight) <= 1) {
            return new Info(true, height);
        }
        return new Info(false, height);
    }

    public class Info{
        public boolean isBalance;
        public int height;

        public Info(boolean isBalance, int height) {
            this.isBalance = isBalance;
            this.height = height;
        }
    }
}
